/*
 * @Author: your name
 * @Date: 2020-10-19 11:43:30
 * @LastEditTime: 2020-11-02 14:32:28
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /Project/node/utils/index.js
 */
const mysql = require('mysql')
const config = require('../config')
const {validationResult } = require('express-validator');
const boom = require('boom');

//连接数据库
function connect() {
    return mysql.createConnection(config)
}

//新建查询连接
function querySql(sql) {

    const conn = connect();
    return new Promise((resolve, reject) => {
        try {
            conn.query(sql, (err, res) => {
                console.log("ssss:");
                if (err) {
                    console.log("措施：",err);
                    reject(err)
                } else {
                    console.log("返回信息:",res);
                    resolve(res)
                }
            })
        } catch (error) {
            console.log("错误信息:",error);
            reject(error)
        } finally {
            console.log("sss:");
            conn.end();
        }
    })
}

//查询一条数据
function queryOne(sql) {
    return new Promise((resolve, reject) => {
        querySql(sql).then(res => {
            if (res && res.length > 0) {
                resolve(res[0]);
            } else {
                resolve(null)
            }
        }).catch(err => {
            reject(err)
        })
    })
}
/**错误处理 */
function guard(req,next,success) {
    const err = validationResult(req);
    // 如果验证错误，empty不为空
    if (!err.isEmpty()) {
        console.log("注意了，有错了:",err);
      // 获取错误信息
      const [{ msg }] = err.errors;
      // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
      next(boom.badRequest(msg));
    } else {
        success()
    }
}

module.exports = {
    querySql,
    queryOne,
    guard
}